//
//  PreferencesWindow.m
//  KotnetAutologin
//
//	handle preference window
//
//  Created by Kristof Marien on 17/01/10.
//  Copyright 2010 KotnetAutologin. All rights reserved.
//

#import "PreferencesWindow.h"

@implementation PreferencesWindow
/**
 *  show the preference window
 */
- (void) show:(id)sender
{
	[NSApp activateIgnoringOtherApps:YES];
	prefWindow = [[NSWindowController alloc] initWithWindowNibName:@"PreferencesWindow"];
	[[prefWindow window] setDelegate:self];
	
	[[prefWindow window] center];
	[prefWindow showWindow:sender];
	userNameTextField = [[[[[[[[prefWindow window] contentView] subviews] objectAtIndex:0] tabViewItemAtIndex:0] view] subviews] objectAtIndex:2];
	passwordTextField = [[[[[[[[prefWindow window] contentView] subviews] objectAtIndex:0] tabViewItemAtIndex:0] view] subviews] objectAtIndex:4];
	saveInKeyChain = [[[[[[[[prefWindow window] contentView] subviews] objectAtIndex:0] tabViewItemAtIndex:0] view] subviews] objectAtIndex:3];
	closeKotnetUnavailable = [[[[[[[[prefWindow window] contentView] subviews] objectAtIndex:0] tabViewItemAtIndex:1] view] subviews] objectAtIndex:0];
	startAtLogin = [[[[[[[[prefWindow window] contentView] subviews] objectAtIndex:0] tabViewItemAtIndex:1] view] subviews] objectAtIndex:1];
	
	KeyChain *keyChain = [KeyChain alloc];
	NSString *password = [keyChain getPasswordKeyChain:[userNameTextField stringValue]];
	if (password != @"not found PWD") {
		[passwordTextField setStringValue:password];
	} else {
		[passwordTextField setStringValue:@""];
		[userNameTextField setStringValue:@""];
	}
	[keyChain dealloc];
}
/**
 *  close the window save changes
 */
- (BOOL)windowShouldClose:(id)sender
{
	NSMutableArray *loginItems;
	
	loginItems = [(NSMutableArray*) CFPreferencesCopyValue((CFStringRef) @"AutoLaunchedApplicationDictionary", (CFStringRef) @"loginwindow", kCFPreferencesCurrentUser, kCFPreferencesAnyHost) autorelease];
	loginItems = [[loginItems mutableCopy]autorelease];
	
	if (!loginItems){
		loginItems=[NSMutableArray arrayWithCapacity:1];
	}
	
	if ([startAtLogin state] && ![self startAlreadyAtLogin]){
		NSDictionary *loginDict=[NSDictionary dictionaryWithObjectsAndKeys:[[NSBundle mainBundle] bundlePath],@"Path",[NSNumber numberWithBool:NO],@"Hide",nil];
		[loginItems addObject:loginDict];
	} else if(![startAtLogin state]){
		int i;
		for (i=0;i<[loginItems count];i++)
			if ([[[[loginItems objectAtIndex:i] objectForKey:@"Path"]stringByStandardizingPath]isEqualToString:[[NSBundle mainBundle]bundlePath]]) break;
		if (i<[loginItems count])
			[loginItems removeObjectAtIndex:i];
	}
	
	CFPreferencesSetValue((CFStringRef) @"AutoLaunchedApplicationDictionary", loginItems, (CFStringRef) @"loginwindow", kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
	CFPreferencesSynchronize((CFStringRef) @"loginwindow",kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
	
	return [self saveLogin:sender];
}
/**
 *  set autostart
 */
- (BOOL) startAlreadyAtLogin
{
	NSArray *loginItems = [(NSArray *) CFPreferencesCopyValue((CFStringRef) @"AutoLaunchedApplicationDictionary", (CFStringRef) @"loginwindow", kCFPreferencesCurrentUser, kCFPreferencesAnyHost) autorelease];
    int i;
    for (i=0;i<[loginItems count];i++)
        if ([[[[loginItems objectAtIndex:i] objectForKey:@"Path"]stringByStandardizingPath]isEqualToString:[[NSBundle mainBundle]bundlePath]]) return YES;
    return NO;
}
/**
 *  save username and password
 */
- (BOOL) saveLogin:(id)sender
{
	KeyChain *keyChain = [KeyChain alloc];
	if ([saveInKeyChain state]) {
		if ([userNameTextField stringValue] == @"" || [passwordTextField stringValue] == @"") {
			[self displayAlertWithMessageText:@"Gelieve een gebruikersnaam en wachtwoord in te vullen.":sender];
			return NO;
		}
		[keyChain savePassWordKeyChain:[userNameTextField stringValue] 
									  :[passwordTextField stringValue]];
	} else {
		[keyChain deletePasswordKeyChain:[userNameTextField stringValue]];
		[userNameTextField setStringValue:@""];
		[passwordTextField setStringValue:@""];
	}
	[keyChain dealloc];
	return YES;
}
/**
 *  display alert
 */
- (void)displayAlertWithMessageText:(NSString *)messageText:(id)sender
{
	NSAlert *alert = [[[NSAlert alloc] init] autorelease];
	[sender setAlphaValue:1.0];
	[alert addButtonWithTitle:@"Ok"];
	[alert setMessageText:@"Foutmelding"];
	[alert setInformativeText:messageText];
	[alert setAlertStyle:NSWarningAlertStyle];
	[alert beginSheetModalForWindow:sender modalDelegate:self didEndSelector:nil contextInfo:nil];
}
- (BOOL)closeWhenKotnetUnavailable
{
	return [closeKotnetUnavailable state];
}

@end
